from fastapi import APIRouter
from server.report.models.model import User
from server.report.utils.mysql_utils import mysql_util 
from server.report.utils.user import my_oauth2_scheme
from server.report.schemas.item import UserItem


router = APIRouter(prefix='/user')


@router.post('/login',tags=['report'])
def login(item: UserItem):
    user_id = item.user_id
    password = item.password

    try:
        uid = int(user_id)
    except Exception:
        return {"code": 1, "msg": "请输入正确的 User ID"}

    with mysql_util.get_db() as db:
        user = db.query(User).filter_by(id=uid).first()

        if not user:
            return {"code": 1, "msg": "查询的用户不存在"}
        else:
            res = user.check_password(password)
            if res:
                access_token = my_oauth2_scheme.create_jwt_token(
                    data={"user_name": user.user_name}
                )
                return {"code": 0, "msg": "登录成功", "access_token": access_token, "username": user.user_name, "uid": uid, "department": user.department}
            else:
                return {"code": 1, "msg": "密码不正确"}